package com.filepublic.demo.server.intercapter;

import com.filepublic.demo.common.constant.ExceptionConstant;
import com.filepublic.demo.common.constant.RedisKeyConstant;
import com.filepublic.demo.common.constant.RedisTimeConstant;
import com.filepublic.demo.common.context.ThreadLocalContext;
import com.filepublic.demo.common.exception.BaseLogicException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class MyIntercapter implements HandlerInterceptor {

    @Resource
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if("OPTIONS".equals(request.getMethod())){
            return true;
        }

        //获取token
        String token = request.getHeader("token");
        log.info("{}",token);

        ValueOperations valueOperations = redisTemplate.opsForValue();
        String userId = (String)valueOperations.get(RedisKeyConstant.TOKEN_KEY + token);

        if(userId == null){
            log.error("登录过期或未登录");
            throw new BaseLogicException(ExceptionConstant.LOGIN_OVER_TIME);
        }
        //将userId保存到线程里
        ThreadLocalContext.setCurrentId(userId);

        //续签
        valueOperations.set(RedisKeyConstant.TOKEN_KEY + token,userId, RedisTimeConstant.TOKEN_TIME, TimeUnit.MILLISECONDS);
        log.info("{}续签成功",userId);

        return true;
    }
}



















